package yuan.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

//按分区粒度同步消息位移
public class ConsumerSync {
    public static final AtomicBoolean isRunning = new AtomicBoolean(true);
    static final int minBatchSize = 200;
    static List<ConsumerRecord> cache = new ArrayList<>();


    public static void main(String[] args) {
        final Properties prop = KafkaConsumerAnalysis.init();
        final KafkaConsumer<String, String> consumer = new KafkaConsumer<>(prop);

        try {
            while (isRunning.get()) {

                final ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                for (TopicPartition partition : records.partitions()) {
                    final List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
                    for (ConsumerRecord<String, String> recordz : partitionRecords) {
                        System.out.println(recordz);

                    }


                    final long lastOffset = partitionRecords.get(partitionRecords.size() - 1).offset();

                    consumer.commitSync(Collections.singletonMap(partition,
                            new OffsetAndMetadata(lastOffset + 1)));


                }


            }
        } finally {
            consumer.close();
        }
    }
}
